<!-- 用户管理 -->
<template>
  <div class="app-container">
    <div class="search-bar">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="创建时间">
          <el-date-picker
              v-model="queryParams.createTime"
              :editable="false"
              class="!w-[240px]"
              type="daterange"
              range-separator="-"
              start-placeholder="开始时间"
              end-placeholder="截止时间"
              value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="旅行社名称" prop="deptId">
          <el-tree-select
              v-model="queryParams.deptId"
              placeholder="全部"
              :data="deptOptions"
              filterable
              clearable
              check-strictly
              :render-after-expand="false"
              style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="关键字" prop="keywords">
          <el-input
              v-model="queryParams.keywords"
              placeholder="用户名/昵称/联系电话"
              clearable
              style="width: 200px"
              @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="search" @click="handleQuery">搜索</el-button>
          <el-button icon="refresh" @click="handleResetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never">
      <div class="flex-x-between mb-10px">
        <div>
          <el-button
              v-hasPerm="['sys:user:add']"
              type="success"
              icon="plus"
              @click="handleOpenDialog()"
          >
            新增
          </el-button>
          <el-button
              v-hasPerm="'sys:user:delete'"
              type="danger"
              icon="delete"
              :disabled="selectIds.length === 0"
              @click="handleDelete()"
          >
            删除
          </el-button>
        </div>
      </div>

      <el-table
          v-loading="loading"
          :data="pageData"
          border
          @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="50" align="center"/>
        <el-table-column type="index" label="序号" width="80" align="center"/>
        <el-table-column label="创建时间" align="center" width="200" prop="createTime"/>
        <el-table-column label="旅行社名称" min-width="250" align="center" prop="deptName"/>
        <el-table-column label="角色名称" min-width="150" align="center" prop="roleNames"/>
        <el-table-column label="登录名" prop="username" min-width="200" align="center"/>
        <el-table-column label="用户昵称" align="center" min-width="200" prop="nickname"/>
        <el-table-column label="性别" width="100" align="center">
          <template #default="scope">
            <!-- 性别字典翻译 -->
            <DictLabel v-model="scope.row.gender" code="gender"/>
          </template>
        </el-table-column>
        <el-table-column label="联系电话" align="center" prop="mobile" min-width="150"/>
        <el-table-column label="操作" fixed="right" align="center" width="220">
          <template #default="scope">
            <el-button
                v-hasPerm="'sys:user:data-scope'"
                type="primary"
                icon="Setting"
                size="small"
                link
                @click="handleDataScope(scope.row.id)"
            >
              自定义数据
            </el-button>
            <el-button
                v-hasPerm="'sys:user:password:reset'"
                type="primary"
                icon="RefreshLeft"
                size="small"
                link
                @click="hancleResetPassword(scope.row)"
            >
              重置密码
            </el-button>
            <el-button
                v-hasPerm="'sys:user:edit'"
                type="primary"
                icon="edit"
                link
                size="small"
                @click="handleOpenDialog(scope.row.id)"
            >
              编辑
            </el-button>
            <el-button
                v-hasPerm="'sys:user:delete'"
                type="danger"
                icon="delete"
                link
                size="small"
                @click="handleDelete(scope.row.id)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
          v-if="total > 0"
          v-model:total="total"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          @pagination="handleQuery"
      />
    </el-card>
    <!-- 用户表单 -->
    <el-dialog
        v-model="dialog.visible"
        width="500px"
        :title="dialog.title"
        @close="handleCloseDialog"
    >
      <el-form ref="userFormRef" :model="formData" :rules="rules" label-width="100px">
        <el-form-item label="旅行社名称" prop="deptId">
          <el-tree-select
              v-model="formData.deptId"
              placeholder="请选择旅行社"
              :data="deptOptions"
              filterable
              check-strictly
              :render-after-expand="false"
              style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="角色名称" prop="roleIds">
          <el-select v-model="formData.roleIds" multiple placeholder="请选择" @change="handleRoleChange">
            <el-option
                v-for="item in roleOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="登录名" prop="username">
          <el-input
              v-model="formData.username"
              :readonly="!!formData.id"
              placeholder="请输入登录名"
              :disabled="!!formData.id"
              maxlength="64"
              show-word-limit
          />
        </el-form-item>
        <el-form-item label="用户昵称" prop="nickname">
          <el-input v-model="formData.nickname" placeholder="请输入用户昵称" maxlength="64" show-word-limit/>
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <Dict v-model="formData.gender" code="gender" style="width: 100%"/>
        </el-form-item>
        <el-form-item label="联系电话" prop="mobile">
          <el-input v-model="formData.mobile" placeholder="请输入联系电话" maxlength="64" show-word-limit/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" :disabled="loading" @click="handleSubmit">确 定</el-button>
          <el-button @click="handleCloseDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>


    <el-dialog
        v-model="dialogDataScope.visible"
        width="500px"
        :title="dialogDataScope.title"
        @close="handleCloseDialogDataScope"
        :close-on-click-modal="false"
    >
      <el-form ref="userFormRefDataScope" :model="formDataDataScope" :rules="rulesDataScope" label-width="100px">
        <el-form-item label="自定义开关">
          <el-radio-group v-model="formDataDataScope.scopeFlag">
            <el-radio :value="1">开启</el-radio>
            <el-radio :value="0">关闭</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="旅行社名称" prop="deptIds" v-if="formDataDataScope.scopeFlag === 1">
          <el-tree-select
              v-model="formDataDataScope.deptIds"
              placeholder="请选择旅行社"
              :data="deptOptions"
              filterable
              multiple
              check-strictly
              :render-after-expand="false"
              style="width: 100%"
          />
        </el-form-item>
<!--        <el-form-item label="旅行社名称" prop="deptIds" v-if="formDataDataScope.scopeFlag === 1">-->
<!--          <el-select-->
<!--              v-model="formDataDataScope.deptIds"-->
<!--              filterable-->
<!--              multiple-->
<!--              remote-->
<!--              reserve-keyword-->
<!--              placeholder="请选择旅行社"-->
<!--              :remote-method="remoteMethod"-->
<!--              :loading="loadingQuery"-->
<!--              style="width: 100%"-->
<!--          >-->
<!--            <el-option-->
<!--                v-for="item in options"-->
<!--                :key="item.value"-->
<!--                :label="item.label"-->
<!--                :value="item.value"-->
<!--            >-->
<!--              <span style="float: left">{{ item.label }}</span>-->
<!--              <span style="float: right; color: var(&#45;&#45;el-text-color-secondary); font-size: 13px;">{{ item.queryCode }}</span>-->
<!--            </el-option>-->
<!--          </el-select>-->
<!--        </el-form-item>-->
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" :disabled="loadingDataScope" @click="handleSubmitDataScope">确 定</el-button>
          <el-button @click="handleCloseDialogDataScope">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import UserAPI, {UserDataScopeFrom, UserForm, UserPageQuery, UserPageVO} from "@/api/system/user";

import DeptAPI from "@/api/system/dept";
import RoleAPI from "@/api/system/role";

defineOptions({
  name: "User",
  inheritAttrs: false,
});
const queryFormRef = ref();
const userFormRef = ref();
const userFormRefDataScope = ref();

const queryParams = reactive<UserPageQuery>({
  pageNum: 1,
  pageSize: 10,
});

const pageData = ref<UserPageVO[]>();
const total = ref(0);
const loading = ref(false);
const loadingDataScope = ref(false);

const list = ref<ListItem[]>([])
const loadingQuery = ref(false)
const options = ref<ListItem[]>([])
interface ListItem {
  value: string
  label: string
  queryCode: string
}
const dialog = reactive({
  visible: false,
  title: "新增用户",
});
const dialogDataScope = reactive({
  visible: false,
  title: "新增用户",
});

const formData = reactive<UserForm>({
  status: 1,
  licence: "3099-12-01",
});

const formDataDataScope = reactive<UserDataScopeFrom>({});

const rules = reactive({
  username: [{required: true, message: "用户名不能为空", trigger: "blur"}],
  nickname: [{required: true, message: "用户昵称不能为空", trigger: "blur"}],
  deptId: [{required: true, message: "所属旅行社不能为空", trigger: "blur"}],
  roleIds: [{required: true, message: "用户角色不能为空", trigger: "blur"}],
});

const rulesDataScope = reactive({
  deptIds: [{required: true, message: "所属旅行社不能为空", trigger: "blur"}],
});

// 选中的用户ID
const selectIds = ref<number[]>([]);
// 部门下拉数据源
const deptOptions = ref<OptionType[]>();
// 角色下拉数据源
const roleOptions = ref<OptionType[]>();
// 导入弹窗显示状态
const importDialogVisible = ref(false);

// 查询
function handleQuery() {
  loading.value = true;
  UserAPI.getPage(queryParams)
      .then((data) => {
        pageData.value = data.list;
        total.value = data.total;
      })
      .finally(() => {
        loading.value = false;
      });
}

// 重置查询
function handleResetQuery() {
  queryFormRef.value.resetFields();
  queryParams.pageNum = 1;
  queryParams.deptId = undefined;
  queryParams.createTime = undefined;
  handleQuery();
}

// 选中项发生变化
function handleSelectionChange(selection: any[]) {
  selectIds.value = selection.map((item) => item.id);
}

function handleRoleChange(selectedValues: any[]) {
  if (selectedValues.length > 1) {
    // 如果选择了多个值，只保留最后一个
    formData.roleIds = [selectedValues[selectedValues.length - 1]];
  }
}

const remoteMethod = (query: string) => {
  if (query) {
    loadingQuery.value = true
    setTimeout(() => {
      loadingQuery.value = false
      options.value = list.value.filter((item) => {
        const q = query.toLowerCase();
        return (
            item.queryCode?.toLowerCase().includes(q) ||
            item.label?.toLowerCase().includes(q)
        );
      })
    }, 200)
  } else {
    options.value = list.value
  }
}

// 重置密码
function hancleResetPassword(row: UserPageVO) {
  ElMessageBox.prompt("请输入用户【" + row.username + "】的新密码", "重置密码", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
  }).then(
      ({value}) => {
        if (!value || value.length < 6) {
          ElMessage.warning("密码至少需要6位字符，请重新输入");
          return false;
        }
        UserAPI.resetPassword(row.id, value).then(() => {
          ElMessage.success("密码重置成功，新密码是：" + value);
        });
      },
      () => {
        ElMessage.info("已取消重置密码");
      }
  );
}

//自定义数据
async function handleDataScope(id?: number) {
  dialogDataScope.visible = true;
  // 加载部门下拉数据源
  deptOptions.value = await DeptAPI.getOptions();
  //await loadDeptOptions()
  if (id) {
    dialogDataScope.title = "自定义数据";
    UserAPI.getFormDataScope(id).then((data) => {
      Object.assign(formDataDataScope, {...data});
    });
  }
}

async function loadDeptOptions() {
  try {
    const allDepts = await DeptAPI.getAllList(); // 获取全部部门数据
    list.value = allDepts.map((item) => {
      return {value: item.id, label: item.name, queryCode: item.queryCode}
    })
    options.value = list.value;
    console.log("获取或处理旅行社数据成功", options.value)
  } catch (error) {
    list.value = [];
    options.value = [];
    console.error("获取或处理旅行社数据失败", error);
  }
}

/**
 * 打开弹窗
 *
 * @param id 用户ID
 */
async function handleOpenDialog(id?: number) {
  dialog.visible = true;
  // 加载角色下拉数据源
  roleOptions.value = await RoleAPI.getOptions();
  // 加载部门下拉数据源
  deptOptions.value = await DeptAPI.getOptions();

  if (id) {
    dialog.title = "修改用户";
    UserAPI.getFormData(id).then((data) => {
      Object.assign(formData, {...data});
    });
  } else {
    dialog.title = "新增用户";
  }
}

// 关闭弹窗
function handleCloseDialog() {
  dialog.visible = false;
  userFormRef.value.resetFields();
  userFormRef.value.clearValidate();

  formData.id = undefined;
  formData.status = 1;
}

function handleCloseDialogDataScope() {
  dialogDataScope.visible = false;
  userFormRefDataScope.value.resetFields();
  userFormRefDataScope.value.clearValidate();
}

// 提交用户表单（防抖）
const handleSubmit = useDebounceFn(() => {
  userFormRef.value.validate((valid: boolean) => {
    // var roleIds = formData.roleIds;
    // const roleArray= roleIds.split(",");
    // formData.roleIds=roleArray;
    //console.log(formData.roleIds);
    if (valid) {
      const userId = formData.id;
      loading.value = true;
      if (userId) {
        UserAPI.update(userId, formData)
            .then(() => {
              ElMessage.success("修改用户成功");
              handleCloseDialog();
              handleResetQuery();
            })
            .finally(() => (loading.value = false));
      } else {
        UserAPI.add(formData)
            .then(() => {
              ElMessage.success("新增用户成功");
              handleCloseDialog();
              handleResetQuery();
            })
            .finally(() => (loading.value = false));
      }
    }
  });
}, 1000);


function beforeSubmit() {
  if (formDataDataScope.scopeFlag === 0) {
    // 删除 deptIds 的验证规则
    delete rulesDataScope.deptIds;
  } else {
    // 添加回 deptIds 的验证规则
    rulesDataScope.deptIds = [{required: true, message: "所属旅行社不能为空", trigger: "blur"}];
  }
}

const handleSubmitDataScope = useDebounceFn(() => {
  userFormRefDataScope.value.validate((valid: boolean) => {
    if (valid) {
      const userId = formDataDataScope.id;
      loadingDataScope.value = true;
      if (userId) {
        UserAPI.updateScope(userId, formDataDataScope)
            .then(() => {
              ElMessage.success("设置成功");
              handleCloseDialogDataScope();
              handleResetQuery();
            })
            .finally(() => (loadingDataScope.value = false));
      }
    }
  });
}, 1000);

/**
 * 删除用户
 *
 * @param id  用户ID
 */
function handleDelete(id?: number) {
  const userIds = [id || selectIds.value].join(",");
  if (!userIds) {
    ElMessage.warning("请勾选删除项");
    return;
  }

  ElMessageBox.confirm("确认删除用户?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(
      function () {
        loading.value = true;
        UserAPI.deleteByIds(userIds)
            .then(() => {
              ElMessage.success("删除成功");
              handleResetQuery();
            })
            .finally(() => (loading.value = false));
      },
      function () {
        ElMessage.info("已取消删除");
      }
  );
}

if (onMounted) {
  onMounted(async () => {
    // 加载区域下拉数据源
    deptOptions.value = await DeptAPI.getOptions();
    handleQuery();
  });
}
</script>
